import { useState,  useRef, useCallback } from 'react';
import qs from 'qs';
import Taro  from '@tarojs/taro';
import request from './request';
import uploadImg from './upload';
import config from './config';

const global = {}

// const file = 'http://192.168.2.120:12800/green-weskit-file/api/file/file/download';
const file = config.filePrefix + '/file/file/download';
function UseFetchRequest(update) {
  const { current } = useRef({});
  const [, setForce] = useState([]);




  // const forceUpdate = useCallback(() => setForce([]),[]);

  const fetch = useCallback(function(info = {}) {
    if (Array.isArray(info)) {
      return Promise.all(
        info.map(item => {
          return new Promise((resolve, reject) => {
            fetch({
              ...item,
              fail: reject,
              callback: resolve,
            });
          });
        })
      );
    }
    const { url, data, header, method, fail, callback } = info;
    request({
      method,
      tartget: url,
      data: data,
      header: header,
    })
      .then(result => {
        callback && callback(result);
      })
      .catch(res => {
        fail && fail(res);
      });
  }, []);

  const setAction = info => {
    for (let k in info) {
      current[k] = info[k];
    }
  }

  // eslint-disable-next-line
  const forceUpdate = info=> {
    setAction(info)
    setForce([])
  }

  const getFileImg = useCallback(({ fileId, fileCode, path }) => {
    const q = {
      Client: config.client || '04',
      fileId: fileId,
      fileCode: fileCode,
      // eslint-disable-next-line
      Authorization: wx.getStorageSync('token'),
    };
    return (
      path ||
      file +
        qs.stringify(q, {
          addQueryPrefix: true,
          allowDots: true,
        })
    );
  }, []);

  const formatTime = useCallback(date => {
    if (!date) {
      return;
    }
    date = new Date(date);
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hour = date.getHours();
    var minute = date.getMinutes();
    var format = function(n) {
      n = n.toString();
      return n[1] ? n : '0' + n;
    };
    var dateList = [year, month, day].map(format);
    return (
      dateList[0] +
      '-' +
      dateList[1] +
      '-' +
      dateList[2] +
      ' ' +
      [hour, minute].map(format).join(':')
    );
  }, []);

  const setUpdate = useCallback(callback => {
    return (function(e) {
      callback && callback(e);
      forceUpdate();
      // update && update([]);
      // ReactDom
    })();
  }, [forceUpdate]);

  const getUpdate = useCallback(
    callback => {
      return e => {
        callback && callback(e);
        update && update([]);
      };
    },
    [update]
  );

  const previewImg = useCallback((url,e)=>{
   const dataset =  e.currentTarget.dataset


    e.stopPropagation();
    let img = url
    let urls = []
    if(Array.isArray(url)){
      img= url[0]
      urls = url
    }else{
      img  = url
      urls = [url]
    }
    if(dataset.index || dataset.index===0){
      img= url[dataset.index]
    }
    Taro.previewImage({
      current: img, urls: urls
    })
  },[])

  const formatDate = useCallback((fmt, date) => {
    if (!date) return date;
    date = new Date(date);
    //author: meizz
    var o = {
      'M+': date.getMonth() + 1, //月份
      'd+': date.getDate(), //日
      'h+': date.getHours(), //小时
      'm+': date.getMinutes(), //分
      's+': date.getSeconds(), //秒
      'q+': Math.floor((date.getMonth() + 3) / 3), //季度
      S: date.getMilliseconds(), //毫秒
    };
    if (/(y+)/.test(fmt))
      fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    for (var k in o)
      if (new RegExp('(' + k + ')').test(fmt))
        fmt = fmt.replace(
          RegExp.$1,
          RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
        );
    return fmt;
  }, []);

  const chooseImage = useCallback(query => {
    uploadImg({
      maxNum: query.num || 5,
      list: query.list || [],
      callback: query.callback,
    });
  }, []);

  const getNavigatorExtra = useCallback(path => {
    if (path) {
      var paramsList = path.split('?').splice(1);
      var queryList = paramsList.join('').split('&');
      var extra = {};
      queryList.forEach(item => {
        const [name, value] = item.split('=');
        extra[name] = value;
      });
      return extra;
    }
    return null;
  }, []);

  return {
    setUpdate,
    getUpdate,
    setAction,
    uploadImg,
    chooseImage,
    getFileImg,
    formatTime,
    formatDate,
    forceUpdate,
    previewImg,
    splitImageFile:getFileImg,
    viewImageFiles:previewImg,
    dateFormat:formatDate,
    global,
    state: current,
    request: fetch,
    getNavigatorExtra,
  };
}

export default UseFetchRequest;
